import sys
sys.path.append("..")
from lib.Spider import Spider
from lib.getExeclPath import getExeclPath

from bs4.element import Tag
from openpyxl.workbook.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet



class Weather(Spider):
    @Spider.Decorators.text
    def getAddress(self):
        return self.bs4.select("body > div.con.today.clearfix > div.left.fl > div:nth-child(1) > div.ctop.clearfix > div.crumbs.fl")

    def getFormatAddress(self):
        arr = self.getAddress().split(">")
        return " >> ".join(list(map(lambda s: s.strip(), arr)))

    def getWeather(self):
        def handle(tag: Tag):
            return {
                **self.getWeatherDate(tag),
                **self.getWeatherWea(tag),
                **self.getWeatherTem(tag),
                **self.getWeatherWin(tag)
            }
        return self.select(".sky", handle)
        

    @Spider.Decorators.field("date")
    @Spider.Decorators.text
    def getWeatherDate(self,weatherTag: Tag):
        return weatherTag.select_one("h1")

    @Spider.Decorators.field("wea")
    @Spider.Decorators.text
    def getWeatherWea(self,weatherTag: Tag):
        return weatherTag.select_one(".wea")

    @Spider.Decorators.field("tem")
    @Spider.Decorators.text
    def getWeatherTem(self,weatherTag: Tag):
        return weatherTag.select_one(".tem")

    @Spider.Decorators.field("win")
    @Spider.Decorators.text
    def getWeatherWin(self,weatherTag: Tag):
        return weatherTag.select_one(".win")

    def appendSheet(self, sheet: Worksheet):
        for weatherDay in self.getWeather():
            sheet.append(list(weatherDay.values()))
    
    def save(self):
        book = Workbook()
        sheet = book.active
        sheet.title = "七日天气"
        self.appendSheet(sheet)
        book.save(getExeclPath("Weather"))


if __name__ == "__main__":
    # 将天气数据保存到 excel 里面 resource\excel\Weather.xlsx
    Weather("http://www.weather.com.cn/weather/101281901.shtml").save()
    
